import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC 连接工具
 *
 * @author shengren.yan
 * @create 2023-08-25
 */
public class JDBCUtils {
    /**
     * 获取数据库的连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
//        //获取配置文件四个基本信息
//        InputStream is = ClassLoader.getSystemClassLoader()
//                .getResourceAsStream("JDBC.properties");
//        Properties properties = new Properties();
//        properties.load(is);
//
//        String user = properties.getProperty("user");
//        String password = properties.getProperty("password");
//        String url = properties.getProperty("url");
//        String driverClass = properties.getProperty("driverClass");

        // 加载驱动
        String url = "jdbc:mysql://localhost:3306/库?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
        String user = "用户名";
        String password = "密码";
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);

        return connection;
    }

    /**
     * 资源的关闭
     *
     * @param connection
     * @param ps
     */
    public static void closeResource(Connection connection, Statement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通用的增删改操作
     *
     * @param sql
     * @param args
     * @throws Exception
     */
    public static void change(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1.获取数据库的连接
            conn = JDBCUtils.getConnection();
            //2.预编译sql语句，返回PreparedStatement实例
            ps = conn.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //4.执行
            ps.execute();
            System.out.println("操作完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            JDBCUtils.closeResource(conn, ps);
        }
    }

    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet resultSet) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
